package com.campus.food.service.impl;

import com.campus.food.mapper.CartMapper;
import com.campus.food.mapper.FoodMapper;
import com.campus.food.mapper.MerchantMapper;
import com.campus.food.mapper.UserMapper;
import com.campus.food.model.entity.Cart;
import com.campus.food.model.entity.Food;
import com.campus.food.model.entity.Merchant;
import com.campus.food.model.entity.User;
import com.campus.food.service.CartService;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class CartServiceImpl implements CartService {
    
    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private FoodMapper foodMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MerchantMapper merchantMapper;
    
    // 购物车项数量限制
    private static final int MAX_CART_ITEMS = 50;
    private static final int MAX_QUANTITY_PER_ITEM = 99;


    @Override
    public List<Map<String, Object>> getUserCartDetail(Long userId) {
        // 检查用户ID
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 获取用户的购物车项
        List<Cart> cartList = cartMapper.selectByUserId(userId);

        // 转换为详细信息列表
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (Cart cart : cartList) {
            // 查询菜品信息
            Food food = foodMapper.selectById(cart.getFoodId());
            // 查询商家信息
            Merchant merchant = merchantMapper.selectById(cart.getMerchantId());

            // 构建详情对象
            Map<String, Object> detailMap = new HashMap<>();
            detailMap.put("id", cart.getId());
            detailMap.put("foodId", cart.getFoodId());
            detailMap.put("userId", cart.getUserId());
            detailMap.put("merchantId", cart.getMerchantId());
            detailMap.put("merchantName", merchant != null ? merchant.getShopName() : "未知商家");
            detailMap.put("name", food != null ? food.getName() : "未知菜品");
            detailMap.put("price", food != null ? food.getPrice() : 0.0);
            detailMap.put("image", food != null ? food.getImage() : "");
            detailMap.put("quantity", cart.getQuantity());
            detailMap.put("remark", cart.getRemark());

            resultList.add(detailMap);
        }

        return resultList;
    }

    @Override
    public Cart addToCart(Cart cart) {
        // 验证必填字段
        validateCart(cart);
        
        // 检查用户是否存在
        User user = userMapper.selectById(cart.getUserId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查菜品是否存在且可购买
        Food food = foodMapper.selectById(cart.getFoodId());
        if (food == null) {
            throw new BusinessException("菜品不存在");
        }
        
        if (food.getStatus() != 1) {
            throw new BusinessException("菜品已下架，无法添加到购物车");
        }
        
        // 设置商家ID
        cart.setMerchantId(food.getMerchantId());
        
        // 检查是否已存在相同菜品
        Cart existingCart = cartMapper.selectByUserIdAndFoodId(cart.getUserId(), cart.getFoodId());
        if (existingCart != null) {
            // 如果已存在，更新数量
            int newQuantity = existingCart.getQuantity() + cart.getQuantity();
            if (newQuantity > MAX_QUANTITY_PER_ITEM) {
                throw new BusinessException("单个菜品数量不能超过" + MAX_QUANTITY_PER_ITEM + "个");
            }
            
            existingCart.setQuantity(newQuantity);
            cartMapper.updateById(existingCart);
            return existingCart;
        } else {
            // 检查购物车项数量限制
            long cartCount = cartMapper.selectCountByUserId(cart.getUserId());
            if (cartCount >= MAX_CART_ITEMS) {
                throw new BusinessException("购物车商品数量已达上限，最多可添加" + MAX_CART_ITEMS + "个商品");
            }
            
            // 新增购物车项
            int result = cartMapper.insert(cart);
            if (result <= 0) {
                throw new BusinessException("添加到购物车失败");
            }
            
            return cart;
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public Cart getCartById(Long id) {
        if (id == null) {
            throw new BusinessException("购物车项ID不能为空");
        }
        
        Cart cart = cartMapper.selectById(id);
        if (cart == null) {
            throw new BusinessException("购物车项不存在");
        }
        
        return cart;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Cart getCartByUserIdAndFoodId(Long userId, Long foodId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (foodId == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        return cartMapper.selectByUserIdAndFoodId(userId, foodId);
    }
    
    @Override
    public boolean updateCartQuantity(Long id, Integer quantity, Long userId) {
        if (id == null) {
            throw new BusinessException("购物车项ID不能为空");
        }
        
        if (quantity == null || quantity <= 0) {
            throw new BusinessException("商品数量必须大于0");
        }
        
        if (quantity > MAX_QUANTITY_PER_ITEM) {
            throw new BusinessException("单个菜品数量不能超过" + MAX_QUANTITY_PER_ITEM + "个");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查购物车项是否存在
        Cart cart = cartMapper.selectById(id);
        if (cart == null) {
            throw new BusinessException("购物车项不存在");
        }
        
        // 验证权限（确保只能修改自己的购物车）
        if (!cart.getUserId().equals(userId)) {
            throw new BusinessException("无权限修改此购物车项");
        }
        
        return cartMapper.updateQuantity(id, quantity) > 0;
    }
    
    @Override
    public boolean removeFromCart(Long id, Long userId) {
        if (id == null) {
            throw new BusinessException("购物车项ID不能为空");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查购物车项是否存在
        Cart cart = cartMapper.selectById(id);
        if (cart == null) {
            throw new BusinessException("购物车项不存在");
        }
        
        // 验证权限（确保只能删除自己的购物车项）
        if (!cart.getUserId().equals(userId)) {
            throw new BusinessException("无权限删除此购物车项");
        }
        
        return cartMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Cart> getCartByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return cartMapper.selectByUserId(userId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Cart> getCartByUserIdAndMerchantId(Long userId, Long merchantId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return cartMapper.selectByUserIdAndMerchantId(userId, merchantId);
    }
    
    @Override
    public boolean clearCart(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return cartMapper.deleteByUserId(userId) >= 0; // 即使没有数据也返回true
    }
    
    @Override
    public boolean clearCartByMerchant(Long userId, Long merchantId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return cartMapper.deleteByUserIdAndMerchantId(userId, merchantId) >= 0; // 即使没有数据也返回true
    }
    
    @Override
    public boolean removeCartBatch(List<Long> ids, Long userId) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("购物车项ID列表不能为空");
        }
        
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 验证所有购物车项都属于当前用户
        for (Long id : ids) {
            Cart cart = cartMapper.selectById(id);
            if (cart == null) {
                throw new BusinessException("购物车项不存在：" + id);
            }
            if (!cart.getUserId().equals(userId)) {
                throw new BusinessException("无权限删除购物车项：" + id);
            }
        }
        
        return cartMapper.deleteByIds(ids) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getCartCount(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return cartMapper.selectCountByUserId(userId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getCartCountByMerchant(Long userId, Long merchantId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return cartMapper.selectCountByUserIdAndMerchantId(userId, merchantId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Cart> getAllCarts(int page, int size, Long userId, Long merchantId) {
        int offset = (page - 1) * size;
        return cartMapper.selectAllForAdmin(offset, size, userId, merchantId);
    }
    
    /**
     * 验证购物车信息
     */
    private void validateCart(Cart cart) {
        if (cart == null) {
            throw new BusinessException("购物车信息不能为空");
        }
        
        if (cart.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (cart.getFoodId() == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
            throw new BusinessException("商品数量必须大于0");
        }
        
        if (cart.getQuantity() > MAX_QUANTITY_PER_ITEM) {
            throw new BusinessException("单个菜品数量不能超过" + MAX_QUANTITY_PER_ITEM + "个");
        }
    }
} 